//
//  SSMainController.swift
//  MyMicroBlog
//
//  Created by stevenSu on 15/7/28.
//  Copyright © 2015年 stevenSu. All rights reserved.
//

import UIKit

class SSMainController: UITabBarController {
    private let pageCount: CGFloat = 5
    override func viewDidLoad() {
        super.viewDidLoad()
        loadChildrenControllers()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let w: CGFloat = tabBar.bounds.width / pageCount
        let x: CGFloat = w * 2
        let y: CGFloat = 0
        let h: CGFloat = tabBar.bounds.height
        composeButton.frame = CGRect(x: x, y: y, width: w, height: h)
    }
    
    private lazy var composeButton: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.addTarget(self, action: "composeButtonClicked", forControlEvents:     UIControlEvents.TouchUpInside)
        self.tabBar.addSubview(btn)
        
        return btn
        }()
    
    /// 点击编辑按钮
    func composeButtonClicked() {
        let vc = SSUserToken.loadToken() == nil ? SSOAuthViewController() : SSComposeViewController()
        let nav = UINavigationController(rootViewController: vc)
        presentViewController(nav, animated: true, completion: nil)
    }
    
    /// 加载所有子控制器
    private func loadChildrenControllers() {
        loadChildController(SSHomeTableViewController(), title: "首页", imgName: "tabbar_home")
        loadChildController(SSMessageTableViewController(), title: "消息", imgName: "tabbar_message_center")
        loadChildController(UIViewController(), title: "", imgName: nil)
        loadChildController(SSDiscoverTableViewController(), title: "发现", imgName: "tabbar_discover")
        loadChildController(SSProfileTableViewController(), title: "我", imgName: "tabbar_profile")
    }

    /// 加载自控制器
    ///
    /// - parameter vc     : 自控制器
    /// - parameter title  : 标题
    /// - parameter imgName: tabbar图标
    private func loadChildController(vc: UIViewController, title: String, imgName: String?) {
        vc.title = title
        let nav = UINavigationController(rootViewController: vc)
        if let name = imgName {
            vc.tabBarItem.image = UIImage(named: name)
        }
        
        addChildViewController(nav)
    }
}
